from flask import Blueprint,request,session,render_template,jsonify,url_for,redirect
from lib.login import user_auth
from models.user import User,Flag,Feedback
from lib.auth import verify_user
from models import db
import random
import traceback
import logging


user_blue = Blueprint('user',__name__,url_prefix='/user')

@user_blue.route('/register_form',methods=["POST","GET"])
def user_register_form():
    if request.method == "POST":
        phone = request.form.get('phone')
        password = request.form.get('password')
        password2 = request.form.get('password2')
        if password != password2:
            return {"msg":"两次密码不对"}
        try:
            user = User(phone=phone,password=password)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('user.user_login_form'))
        except Exception as e:
            print(e)
    return render_template("user_register.html")

@user_blue.route('/login_form',methods=["POST","GET"])
def user_login_form():
    if request.method == "POST":
        phone = request.form.get("phone")
        password = request.form.get('password')
        auth = verify_user(phone,password)
        if auth:
            session["phone"] = phone
            session['uid'] = auth.id
            session['role'] = 'user'
            return redirect(url_for('user.user_index'))
        else:
            return "login failed"
    return render_template('user_login.html')

@user_blue.route('/index')
def user_index():
    return {"code":20001,"msg":"hello:"+session.get('phone')}

# @user_blue.route('/deposit',methods=['POST'])
# @user_auth
# def deposit():
#     data =  request.json
#     code = data.get('code')
#     try:
#         flag = Flag.query.filter_by(code=code).first()
#         print("isused:" + str(flag.isused), "user_id:" + str(flag.user_id))
#         if not flag or flag.isused is True: #表示无该充值码不可用
#             return {"code":40001,"msg":"code not useful"}
#         else:
#             user_id = session.get('uid')
#             flag.user_id = user_id
#             flag.isused = True
#             db.session.add(flag)
#             db.session.commit()
#             user = User.query.filter_by(id=user_id).first()
#             user.money = user.money+flag.price
#             db.session.add(user)
#             db.session.commit()
#         return jsonify({"msg":"success"})
#     except Exception as e:
#         db.session.rollback()
#         raise e

@user_blue.route('/exchange',methods=['POST'])
@user_auth
def exchange():
    data =  request.json
    code = data.get('code')
    try:
        flag = Flag.query.filter_by(code=code).first()
        if not flag or flag.isused is True:
            return {"code":40001,"msg":"code not useful"}
        else:
            flag.user_id = session.get('uid')
            flag.isused = True
            db.session.add(flag)
            user = User.query.filter_by(id=session.get('uid')).first()
            user.money = user.money+flag.price
            db.session.add(user)
            db.session.commit()
            return jsonify({"code":10001,"msg":"exchange success"})
    except Exception as e:
        db.session.rollback()
        logging.error(time.strftime('%y-%m-%d %H:%M:%S') + traceback.format_exc())

